﻿using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections.Generic;

namespace MyMailWp8.Protocol
{
    /*
    public delegate CMPopAttDownloadInfo CallBackGetAttDownloadInfo();

    public class CMPopAttDownloadInfo
    {
        public Attachment attachment;
        public bool bPreview;
    }

    internal class CMPopFetchAttachment : CMPopBase
    {
        private int _ReceiveState = 0;//0-init,1-get ok flag,2-receive mime data,3－get convert list

        private String _stringRawDatabuf;

        internal event CallBackGetAttDownloadInfo GetAttDownloadInfo;
        bool _blist = false;

        public CMPopFetchAttachment(AsyncSocketClient sockClient)
            : base(sockClient)
        {
            ;
        }

        public bool GetAttachmentData()
        {
            _stringRawDatabuf = null;
            _ReceiveState = 0;

            CMPopAttDownloadInfo attInfo = GetAttDownloadInfo();
            if (attInfo == null)
                return false;

            string type = "";
            _blist = false;
            if (attInfo.bPreview)
            {
                bool bret = PEUtility.canConvert(attInfo.attachment.originalFilename, out type, ref _blist);
                if (!bret)
                    return false; //不支持预览的文件类型
            }

            string attDownloadCommand = "ERET ";
            attDownloadCommand += Convert.ToString(attInfo.attachment.emailUid) + " " + attInfo.attachment.contentId;
            if (type != "")
            {
                attDownloadCommand += " " + type;
                //2012-10-19,
                if ((attInfo.bPreview) && (!_blist))//图片预览
                {
                    string file = IsolateStorageUtil.GetImageAttachmentPreviewFile(attInfo.attachment);
                    IsolateStorageUtil.DeleteFile(file);
                }
            }
            else
            {
                string strOffset = string.Format(" ORIGINAL {0} {1}", attInfo.attachment.downloadSize, attInfo.attachment.totalSize - attInfo.attachment.downloadSize);
                attDownloadCommand += strOffset;
            }

            attDownloadCommand += " \r\n";
            SendData(attDownloadCommand);

            return true;
        }

        override public int ParseData(String inString)
        {
            if (inString == null)
                return 0;

            if (_stringRawDatabuf == null)
                _stringRawDatabuf = String.Copy(inString);
            else
                _stringRawDatabuf += inString;

            int nTrimpos = 0;
            switch (_ReceiveState)
            {
                //_ReceiveState:  0-got ok flag,1-receive data
                case 0:
                    {
                        nTrimpos = _stringRawDatabuf.IndexOf("\r\n");
                        if (nTrimpos == -1)
                            return 0;

                        if (_stringRawDatabuf.ToUpper().StartsWith("+OK") == true)
                        {
                            _ReceiveState = 1;
                            nTrimpos += 2;//pass away "/r/n"
                            _stringRawDatabuf = _stringRawDatabuf.Substring(nTrimpos);

                            GetReponsedata();
                        }
                        else
                        {
                            int errCode = ParseCMPopErr(_stringRawDatabuf);
                            string strErr = PostServerRetError(errCode);

                            // DefaultLogger.Log.LogDebug("CMPopFetchAttachment:ParseData case 0" + _stringRawDatabuf + "\r\n");
                        }
                    }
                    break;

                case 1://get raw data
                    {
                        GetReponsedata();
                    }
                    break;

                default:
                    break;
            }

            return 0;
        }

        private bool GetReponsedata()
        {
            if (_stringRawDatabuf.EndsWith(".\r\n") != true)
            {
                SaveAttachmentData(false);
                ReceiveData();
                return false;
            }

            //got the all raw data,finish receive one attachment
            _stringRawDatabuf = _stringRawDatabuf.Remove(_stringRawDatabuf.Length - 3);

            //save mail data to DB
            SaveAttachmentData(true);

            //release resource for previous mail data
            _stringRawDatabuf = null;

            int nState = (int)(CMPopState.CMPOP_RecvedOneAttachment);
            if (_blist)
                nState = (int)(CMPopState.CMPOP_RecvedOneAttachmentConvertList);

            ChangeCMPopSmtpState(nState);

            //have more att to download?
            CMPopAttDownloadInfo attInfo = GetAttDownloadInfo();
            if (attInfo != null)
            {
                GetAttachmentData();
            }
            else
            {
                nState = (int)(CMPopState.CMPOP_Quit);
                ChangeCMPopSmtpState(nState);
            }

            return true;
        }


        private bool SaveAttachmentData(bool bEnd)
        {
            bool bRet = false;
            CMPopAttDownloadInfo attInfo = GetAttDownloadInfo();
            if (attInfo != null)
            {
                if (_blist)
                {
                    if (bEnd)
                        bRet = saveConvertList(attInfo.attachment);
                }
                else
                    bRet = SaveReceivedAttachment(attInfo, bEnd);
            }
            else
            {
               // DefaultLogger.Log.LogDebug("GetAttachment GetReponsedata" + "\r\n"); ;
            }
            return bRet;
        }

        private bool SaveReceivedAttachment(CMPopAttDownloadInfo attachInfo, bool bEnd)
        {
            bool bRet = false;
            try
            {

                Attachment attachment = attachInfo.attachment;
                String strMod = "";
                if (!bEnd)
                {
                    //查找base64编码字符串的一整行，一行76个字符+"\r\n"
                    int len = _stringRawDatabuf.Length;
                    if (len < 78)
                        return bRet;
                    int mod = len % 78;
                    if (mod != 0)
                    {
                        strMod = _stringRawDatabuf.Substring(len - mod, mod);
                        _stringRawDatabuf = _stringRawDatabuf.Remove(len - mod);
                    }
                }

                byte[] buffer = Convert.FromBase64String(_stringRawDatabuf);
                if ((buffer == null) || (buffer.Length == 0))
                    return bRet;

                _stringRawDatabuf = strMod;

                string strPath = IsolateStorageUtil.GetAttachmentPath(attachment);

                string fileName = attachment.localFile;
                if (string.IsNullOrEmpty(fileName))//兼容老版本
                    fileName = attachment.originalFilename;
                bool bUpdate = true;
                if ((attachInfo.bPreview) && (!_blist))//图片预览
                {
                    fileName += IsolateStorageUtil.IMAGE_PREVIEW_EXT;
                    bUpdate = false;
                }
                IsolateStorageUtil.SaveRawDataFile(strPath, fileName, buffer, FileMode.Append);
                if (!bUpdate)
                    return true;

                try
                {
                    CMPopAttDownloadInfo attInfo = GetAttDownloadInfo();
                    PeDataModel peDataModel = PEDBManager.Instance().peDataModel;
                    int downloadSize = attInfo.attachment.downloadSize + buffer.Length;
                    attachment.downloadSize = downloadSize;
                    peDataModel.updateAttchment(attInfo.attachment.emailId, attInfo.attachment.contentId, downloadSize,bEnd);
                    AttachmentDownloadProcess(attachment);
                    bRet = true;
                }
                catch (Exception ex)
                {
                    //DefaultLogger.Log.LogDebug(ex.ToString());
                }
            }
            catch (Exception e)
            {
                //DefaultLogger.Log.LogDebug(e.ToString());
            }
            return bRet;
        }

        private bool saveConvertList(Attachment parentAttachment)
        {
            byte[] buffer = Convert.FromBase64String(_stringRawDatabuf);
            string messageContent = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

            using (StringReader messageReader = new StringReader(messageContent))
            {
                string line;
                string boundary = "";
                while ((line = messageReader.ReadLine()) != null)
                {
                    if (line == "")
                        continue;

                    int pos = line.IndexOf("boundary");
                    if (pos > 0)
                    {
                        pos = line.IndexOf('=', pos);
                        if (pos > 0)
                        {
                            pos++;
                            boundary = line.Substring(pos);
                            boundary = boundary.Trim();                         //去掉空格
                            boundary = boundary.Trim(new char[1] { '\"' });     //去掉引号
                            break;
                        }
                    }
                }
                if (boundary == "")
                    return false;

                Attachment newAttachment = null;
                int i = 0;
                while ((line = messageReader.ReadLine()) != null)
                {
                    if (line == "")
                        continue;
                    if (line.IndexOf(boundary) > 0) //一个新的boundary开始
                    {
                        i++;
                        if (newAttachment != null)
                        {
                            PEDBManager.Instance().peDataModel.AddMailAttInfo(ref newAttachment);
                        }
                        newAttachment = new Attachment();
                        newAttachment.emailId = parentAttachment.emailId;
                        newAttachment.emailUid = parentAttachment.emailUid;
                        newAttachment.parentContentId = parentAttachment.contentId;
                        newAttachment.downloadSize = 0;
                        newAttachment.accountId = parentAttachment.accountId;
                        newAttachment.mimeTime = parentAttachment.mimeTime;
                        //目前预览只转换为png这种比较小的文件格式；以后有设置以后根据修改。预览文件保存格式为：xxxx.doc-1.png
                        newAttachment.localFile = parentAttachment.originalFilename + "-" + i.ToString() + ".png";

                    }
                    string key = string.Empty;
                    string value = string.Empty;

                    int indexOfColon = line.IndexOf(':');

                    // Check if it is allowed to make substring calls
                    if (indexOfColon >= 0 && line.Length >= indexOfColon + 1)
                    {
                        key = line.Substring(0, indexOfColon).Trim();
                        value = line.Substring(indexOfColon + 1).Trim();
                        if (key == "Content-ID")
                            newAttachment.contentId = value;
                        if (key == "Content-Type")
                        {
                            int pos = value.IndexOf('=');
                            if (pos > 0)
                            {
                                pos++;
                                newAttachment.originalFilename = PushEmail.Mime.Decode.EncodedWord.Decode(value.Substring(pos).Trim(new char[2] { ' ', '\"' }));//??????
                            }
                        }
                    }

                }

            }

            return true;
        }
    }
     
     */
}
